package com.zhang.servicepay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.zhang.servicepay.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 类功能描述
 *
 * @author Kye
 * @date 2025-04-20
 */
@RequestMapping("/alipay")
@Controller
@ResponseBody
public class AliPayController {

	@GetMapping("/pay")
	public String pay(String subject, String outTradeNo, String totalAmount) {
		AlipayTradePagePayResponse pay;
		try {
			pay = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return pay.getBody();
	}

	@Autowired
	AlipayService alipayService;

	@PostMapping("/notify")
	public String notify(HttpServletRequest httpServletRequest) throws Exception {
		String tradeStatus = httpServletRequest.getParameter("trade_status");

		if (tradeStatus.trim().equals("TRADE_SUCCESS")) {
			HashMap<String,String> map = new HashMap<>();
			Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
			for (String name : parameterMap.keySet()) {
				map.put(name,httpServletRequest.getParameter(name));
			}

			if (Factory.Payment.Common().verifyNotify(map)){
				System.out.println("通过支付宝的验证");
				// for (String name : map.keySet()) {
				// 	System.out.println("收到并且接收好的参数");
				// 	System.out.println(name+":"+map.get(name));
				// }

				String out_trade_no = map.get("out_trade_no");
				Long orderId = Long.parseLong(out_trade_no);

				alipayService.pay(orderId);

			}else{
				System.out.println("支付宝验证不通过");
			}
		}
		return "success";
	}
}
